package com.yong.common.id;
/**
 * 生成项目中用到的UUID
 * @author Majian
 */
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
//
public class SequenceCreator {
	private SecureRandom seeder = null;
	private String midString;
	
	public SequenceCreator() 
	{		
	}

	private void init() 
	{
		try {
			InetAddress inet = InetAddress.getLocalHost();
			byte[] bytes = inet.getAddress();

			String hexAddress = hexFormat(getInt(bytes), 8);
			String hash = hexFormat(System.identityHashCode(this), 8);

			midString = hexAddress + hash;

			seeder = new SecureRandom();
			seeder.nextInt();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	synchronized public String getUID()
	{
		init();
		StringBuffer buf = new StringBuffer();
	
		long time = System.currentTimeMillis();
		int timeLow = (int) time & 0xFFFFFFFF;
		int node = seeder.nextInt();
	
		buf.append(hexFormat(timeLow, 8)).append(midString).append(hexFormat(node, 8));
	
		return buf.toString();
	}

	
	

	private String hexFormat(int number, int digits) {
		// TODO Auto-generated method stub
		String hex = Integer.toHexString(number).toUpperCase();
		
		if (hex.length() >= digits) {
			return hex.substring(0, digits);
		} else {
			return hex;
		}

	}

	private int getInt(byte[] bytes) {
		int size = (bytes.length > 32) ? 32 : bytes.length;
		int result = 0;

		for (int i = size - 1; i >= 0; i--) {
			if (i == (size - 1))
				result += bytes[i];
			else
				result += (bytes[i] << 4 * (size - 1 - i));
		}
		return result;

	}
	
	/**
	 * 随机产生密码
	 * @param digits 产生的密码的长度
	 * @param lowerCase 是否输出为小写的密码
	 * @return
	 */
	synchronized public String getPassword(int digits, boolean lowerCase) {
		if (seeder == null) {
			seeder = new SecureRandom();
		}
		int node = seeder.nextInt();

		String tmpPass = hexFormat(node, digits);

		if (lowerCase)
			return tmpPass.toLowerCase();
		else
			return tmpPass;
	}
	
	/**
	 * 得到指定个数的随机的数字,位数不够，会在前面添加0
	 * @param digits 产生随机数字的长度 
	 * @return
	 */
	synchronized public String getInt(int digits) {
		if (seeder == null) {
			seeder = new SecureRandom();
		}
		int maxInt = (int) Math.pow(10, digits);
		int random = seeder.nextInt(maxInt - 1);

		if (Integer.toString(random).length() == digits) {
			return Integer.toString(random);
		}

		// 假如是一个数字的话，那就重新产生一下
		if(Integer.toString(random).length() == 1){
			return getInt(digits);
		}
		
		StringBuilder sb = new StringBuilder();

		for (int i = Integer.toString(random).length(); i < digits; i++) {
			sb.append("0");
		}
		
		return sb.toString() + random;
	}	
	
	public static void main(String [] s){
		SequenceCreator sc = new SequenceCreator();
		for(int i = 0; i < 100; i++)
			System.out.println(sc.getInt(6));	
	}
}
